package org.zjx.window.operation.impl;


import org.zjx.window.operation.BaseOperationExecutor;
import org.zjx.window.window.IWindow;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Objects;

/**
 * 基于Robot的操作执行器实现
 * 提供具体的图像识别和颜色查找实现
 *
 * @author zjx
 * @since 1.0
 */
public class RobotOperator extends BaseOperationExecutor {

    /**
     * 默认构造方法
     */
    public RobotOperator() {
        super();
    }

    /**
     * 带窗口的构造方法
     *
     * @param window 关联窗口
     */
    public RobotOperator(IWindow window) {
        super(window);
    }

    /**
     * 检查图像中是否包含指定颜色
     *
     * @param image       要检查的图像
     * @param targetColor 目标颜色
     * @return 如果包含目标颜色返回true，否则返回false
     */
    private boolean containsColor(BufferedImage image, Color targetColor) {
        int targetRGB = targetColor.getRGB();
        int width = image.getWidth();
        int height = image.getHeight();

        // 简单的逐像素检查
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (image.getRGB(x, y) == targetRGB) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取指定区域的平均颜色
     *
     * @param region 区域
     * @return 平均颜色
     */
    public Color getAverageColor(Rectangle region) {
        Objects.requireNonNull(region, "区域不能为 null");

        try {
            BufferedImage screenshot = screenshot(region);
            return calculateAverageColor(screenshot);
        } catch (Exception e) {
            System.err.println("获取平均颜色失败: " + e.getMessage());
            return Color.BLACK;
        }
    }

    /**
     * 计算图像的平均颜色
     *
     * @param image 图像
     * @return 平均颜色
     */
    private Color calculateAverageColor(BufferedImage image) {
        long totalRed = 0;
        long totalGreen = 0;
        long totalBlue = 0;

        int width = image.getWidth();
        int height = image.getHeight();
        int totalPixels = width * height;

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                Color pixelColor = new Color(image.getRGB(x, y));
                totalRed += pixelColor.getRed();
                totalGreen += pixelColor.getGreen();
                totalBlue += pixelColor.getBlue();
            }
        }

        int avgRed = (int) (totalRed / totalPixels);
        int avgGreen = (int) (totalGreen / totalPixels);
        int avgBlue = (int) (totalBlue / totalPixels);

        return new Color(avgRed, avgGreen, avgBlue);
    }
}